﻿Imports System.Runtime.InteropServices
Imports System.Text

Public Class Parser
    'default domitis 
    Public Sub New()
    End Sub

    'fortoma tou filtrou
    <DllImport("query.dll", CharSet:=CharSet.Unicode)> _
    Private Shared Function LoadIFilter(ByVal pwcsPath As String, ByRef pUnkOuter As IUnknown, ByRef ppIUnk As IFilter) As Integer
    End Function

    <ComImport(), Guid("00000000-0000-0000-C000-000000000046")> _
    <InterfaceType(ComInterfaceType.InterfaceIsIUnknown)> _
    Private Interface IUnknown
        <PreserveSig()> _
        Function QueryInterface(ByRef riid As Guid, ByRef pVoid As IntPtr) As IntPtr

        <PreserveSig()> _
        Function AddRef() As IntPtr

        <PreserveSig()> _
        Function Release() As IntPtr
    End Interface

    'iperfortomeni methodos filtrou
    Private Shared Function loadIFilter(ByVal filename As String) As IFilter
        Dim iunk As IUnknown = Nothing
        Dim filter As IFilter = Nothing

        ' Try to load the corresponding IFilter 
        Dim resultLoad As Integer = loadIFilter(filename, iunk, filter)
        If resultLoad <> CInt(IFilterReturnCodes.S_OK) Then
            Return Nothing
        End If
        Return filter
    End Function


    Public Shared Function IsParseable(ByVal filename As String) As Boolean
        Return loadIFilter(filename) IsNot Nothing
    End Function

    'methodos analisis filtrou
    Public Shared Function Parse(ByVal filename As String) As String
        Dim filter As IFilter = Nothing

        Try
            Dim plainTextResult As New StringBuilder()
            filter = loadIFilter(filename)

            Dim ps As New STAT_CHUNK()
            Dim mFlags As IFILTER_INIT = 0

            Dim i As UInteger = 0
            filter.Init(mFlags, 0, Nothing, i)

            Dim resultChunk As Integer = 0


            resultChunk = filter.GetChunk(ps)
            While resultChunk = 0
                If ps.flags = CHUNKSTATE.CHUNK_TEXT Then
                    Dim sizeBuffer As UInteger = 60000
                    Dim resultText As Integer = 0
                    While resultText = Constants.FILTER_S_LAST_TEXT OrElse resultText = 0
                        sizeBuffer = 60000
                        Dim sbBuffer As New System.Text.StringBuilder(CInt(sizeBuffer))
                        resultText = filter.GetText(sizeBuffer, sbBuffer)

                        If sizeBuffer > 0 AndAlso sbBuffer.Length > 0 Then
                            Dim chunk As String = sbBuffer.ToString(0, CInt(sizeBuffer))
                            plainTextResult.Append(chunk)
                        End If
                    End While
                End If
                resultChunk = filter.GetChunk(ps)
            End While
            Return plainTextResult.ToString()
        Finally
            If filter IsNot Nothing Then
                Marshal.ReleaseComObject(filter)
            End If
        End Try
    End Function
End Class